from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker

from config.config import DatabaseConfig

engine = create_async_engine(
    DatabaseConfig.url,
    echo=True,  # 打印 SQL 语句，用于调试
    pool_size=20,  # 连接池大小
    max_overflow=2,  # 允许的最大溢出连接数
    pool_timeout=30,  # 等待连接的最大时间（秒）
    pool_recycle=1800,  # 连接的最大存活时间（秒）
)

SessionLocal = sessionmaker(engine, class_=AsyncSession, autocommit=False, autoflush=False, )

async def get_session():
    async with SessionLocal() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise
        finally:
            await session.close()
